<?php

namespace Wap\Controller;

use User\Model\LotteryModel;
use Wap\Model\StatisticsModel;
use Wap\Service\WeixinService;

class LotteryController extends WapController
{
    private $_wxuser;
    private $_project;
    private $_token;

    public function __construct()
    {
        $this->_project = 'lottery';
        if($_SERVER['HTTP_HOST'] == "192.168.1.137") {         //本地
            $openid = get_client_ip();
            $id = (I('get.id', -1)==-1) ? I('post.id', -1) : I('get.id', -1);
            session('lottery_openid_'.$id, $openid);
            session('lottery_sex_'.$id, 1);
            session('lottery_city_'.$id, '');
            $where['id'] = $id;
            $lottery = M('redpacket')->where($where)->find();
            if(empty($lottery)){
                header("Content-type: text/html; charset=utf-8");
                die('活动不存在');
            }
            $this->_token = $lottery['token'];
            $this->_registerFans($id);
        }
        parent::__construct();
    }

    public function index()
    {
        $code = I('get.code', '');
        $id = I('get.id', "", "");
        $where['id'] = $id;
        $where['keyword'] = $this->_project;
        $where['status'] = LotteryModel::STATUS_ACTIVE;
        $lottery = M('redpacket')->where($where)->field('token,share_title,share_desc,share_link,share_img')->find();
        if(empty($lottery)){
            header("Content-type: text/html; charset=utf-8");
            die('活动不存在');
        }
        $wxShare = array(
            'share_title' => $lottery['share_title'],
            'share_desc' => $lottery['share_desc'],
            'share_link' => !empty($lottery['share_link']) ? $lottery['share_link'] :
                C('SITE_URL').'/Wap/Lottery/index?id='.$id,
            'share_image' => C('SITE_URL').$lottery['share_img'],
        );
        $wxConfig = array();
        $openid = session('lottery_openid_'.$id);
        $this->_token = $lottery['token'];
        if($this->_isWx()){
            $this->_wxuser = WeixinService::getWxuser($lottery['token']);
            if($code){
                $wechat = new \Wap\Service\WechatService($this->_wxuser['appid'], $this->_wxuser['appsecret']);
                $out = $wechat->snsapiUserInfo($this->_wxuser['appid'], $this->_wxuser['appsecret'], $code);
                if( !empty($out['openid']) ){
                    session('lottery_openid_'.$id, $out['openid']);
                    session('lottery_avatar_'.$id, $out['headimgurl']);
                    session('lottery_nickname_'.$id, $out['nickname']);
                    session('lottery_sex_'.$id, $out['sex']);
                    session('lottery_city_'.$id, $out['city']);
                    $this->_registerFans($id);
                }else{
                    $choice = I("get.choice", "", "");
                    if($choice < 3){
                        $choice++;
                        $wechat = new \Wap\Service\WechatService($this->_wxuser['appid'], $this->_wxuser['appsecret']);
                        $forward = C('SITE_URL').'/Wap/Lottery/index?id=' . $id . "&choice=" . $choice;
                        $url = $wechat->snsapiUserInfoLink($forward, $this->_wxuser['appid']);
                        redirect($url);
                    }
                }
                $wxJSApi = WeixinService::buildWXJSApi($this->_wxuser);
                if(!empty($wxJSApi)){
                    $wxConfig = array(
                        'appId' => $this->_wxuser['appid'],
                        'nonceStr' => $wxJSApi['noncestr'],
                        'timestamp' => $wxJSApi['timestamp'],
                        'signature' => $wxJSApi['sha1']
                    );
                }
                $this->assign('wxConfig', $wxConfig);
                $this->assign('wxShare', $wxShare);
                StatisticsModel::visit("lottery", $id);
                $this->display();
            }else{
                if($openid){
                    $wxJSApi = WeixinService::buildWXJSApi($this->_wxuser);
                    if(!empty($wxJSApi)){
                        $wxConfig = array(
                            'appId' => $this->_wxuser['appid'],
                            'nonceStr' => $wxJSApi['noncestr'],
                            'timestamp' => $wxJSApi['timestamp'],
                            'signature' => $wxJSApi['sha1']
                        );
                    }
                    $this->assign('wxConfig', $wxConfig);
                    $this->assign('wxShare', $wxShare);
                    StatisticsModel::visit("lottery", $id);
                    $this->display();
                }else{
                    $wechat = new \Wap\Service\WechatService($this->_wxuser['appid'], $this->_wxuser['appsecret']);
                    $forward = C('SITE_URL').'/Wap/Lottery/index?'.$_SERVER['QUERY_STRING'];
                    $url = $wechat->snsapiUserInfoLink($forward, $this->_wxuser['appid']);
                    redirect($url);
                }
            }
        }else{
            if(!$openid){
                if(cookie("token")){
                    $openid = cookie("token");
                }else{
                    $openid = $this->_getRandCode();
                    cookie("token", $openid, 60 * 60 * 24 * 30);//一个月
                }
                session('lottery_openid_'.$id, $openid);
                session('lottery_avatar_'.$id, '');
                session('lottery_nickname_'.$id, "游客_".$openid);
                session('lottery_sex_'.$id, 0);
                session('lottery_city_'.$id, '');
                $this->_registerFans($id);
            }
            $this->assign('wxConfig', $wxConfig);
            $this->assign('wxShare', $wxShare);
            StatisticsModel::visit("lottery", $id);
            $this->display();
        }
    }

    //判断是否微信端
    private function _isWx() {
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
            return true;
        }
        return false;
    }

    //随机生成字符串
    private function _getRandCode()
    {
        $charts = "abcdefghjkmnpqrstuvwxyz0123456789";
        $max = strlen($charts);
        $noncestr = "";
        for($i = 0; $i < 7; $i++)
        {
            $noncestr .= $charts[mt_rand(0, $max)];
        }
        return $noncestr;
    }

    //记录粉丝信息
    private function _registerFans($id)
    {
        $openid = session('lottery_openid_'.$id);
        $where['token'] = $this->_token;
        $where['pid'] = $id;
        $where['openid'] = $openid;
        $where['status'] = LotteryModel::FANS_ACTIVE;
        $fans = M('redpacket_fans')->where($where)->find();
        if(empty($fans)){
            $data = array(
                'token' => $this->_token,
                'pid' => $id,
                'openid' => $openid,
                'reserve' => 0,//分享次数
                'sex' => session('lottery_sex_'.$id) ? session('lottery_sex_'.$id) : 0,
                'city' => session('lottery_city_'.$id) ? session('lottery_city_'.$id) : '未知',
                'phone_type' => $this->_phoneType()
            );
            M('redpacket_fans')->add($data);
        }
    }

    //抽奖活动状态
    public function getLotteryStatus()
    {
        $id = I('get.id', -1);
        if($id == -1){
            $this->ajaxReturn(array('code' => 101, 'errMsg' => 'required parameter missing'));
        }
        $where['id'] = $id;
        $where['keyword'] = $this->_project;
        $where['status'] = LotteryModel::STATUS_ACTIVE;
        $lottery = M('redpacket')->where($where)->field('startdate,enddate')->find();
        if(!empty($lottery)){
            $time = date('Y-m-d H:i:s');
            if($lottery['startdate'] > $time){
                $this->ajaxReturn(array('code' => 103, 'errMsg' => 'not start'));
            }elseif($time > $lottery['enddate']){
                $this->ajaxReturn(array('code' => 104, 'errMsg' => 'already end'));
            }else{
                $this->ajaxReturn(array('code' => 0, 'errMsg' => 'ok'));
            }
        }else{
            $this->ajaxReturn(array('code' => 102, 'errMsg' => 'invalid id'));
        }
    }

    //抽奖活动基本信息
    public function getLotteryInfo()
    {
        $id = I('get.id', -1);
        if($id == -1){
            $this->ajaxReturn(array('code' => 101, 'errMsg' => 'required parameter missing'));
        }
        $openid = session('lottery_openid_'.$id);
        if(!$openid){
            $this->ajaxReturn(array('code' => 108, 'errMsg' => 'openid missing'));
        }
        $where['id'] = $id;
        $where['keyword'] = $this->_project;
        $where['status'] = LotteryModel::STATUS_ACTIVE;
        $lottery = M('redpacket')->where($where)->find();
        if(!empty($lottery)){
            $turntable = $this->_turnTable($id);
            $turntables = array();
            if(!empty($turntable)){
                foreach ($turntable as $value){
                    $table = '';
                    if($value['level'] != 0){
                        $table = array(
                            'level' => LotteryModel::getLevel($value['level']),
                            'name' => $value['name']
                        );
                    }
                    $turntables[$value['order']] = $table;
                }
            }
            $force_follow = ($lottery['game_time']==LotteryModel::FOLLOW_YES) ? 1 : 0;
            $force_image = !empty($lottery['picurl']) ? C('SITE_URL').$lottery['picurl'] : '';
            $img_data = json_decode($lottery['desc'], true);
            $img_background = C('SITE_URL').$img_data['img-background'];
            $img_accept = C('SITE_URL').$img_data['img-accept'];
            $img_again = C('SITE_URL').$img_data['img-again'];
            $img_share = C('SITE_URL').$img_data['img-share'];
            $img_custom = C('SITE_URL').$img_data['img-custom'];
            $custom_choose = $img_data['custom-choose'];
            $img_code = !empty($img_data['img-code']) ? C('SITE_URL').$img_data['img-code'] : '';
            $custom_link = $img_data['custom-link'];
            //关注公众号状态
            $this->_wxuser = WeixinService::getWxuser($lottery['token']);
            $follow_status = $this->_followStatus($id);
            if($follow_status){
                $follow_status = 1;
            }else{
                $follow_status = 0;
            }
            //抽奖剩余次数
            $game_chance1 = $game_chance2 = 0;
            $day_start = date("Y-m-d") . " 00:00:00";
            $day_end = date("Y-m-d") . " 23:59:59";
            $award = M('redpacket_fansaward');
            $number_limits = intval($lottery['number_limits']); //每日游戏次数上限
            $per_num = intval($lottery['per_num']);             //每人每日游戏次数上限
            if($number_limits != -1){
                $where_limit['pid'] = $lottery['id'];
                $where_limit['status'] = array('neq', LotteryModel::AWARD_DELETE);
                $where_limit['createdate'] = array('between', array($day_start, $day_end));
                $number_limits_record = $award->where($where_limit)->count();
                $game_chance1 = $number_limits - $number_limits_record;
                if($game_chance1 < 0){
                    $game_chance1 = 0;
                }
            }
            if($per_num != -1){
                $where_per['pid'] = $lottery['id'];
                $where_per['openid'] = $openid;
                $where_per['status'] = array('neq', LotteryModel::AWARD_DELETE);
                $where_per['createdate'] = array('between', array($day_start, $day_end));
                $where_per['reserve'] = LotteryModel::LOTTERY_NORMAL;
                $per_num_record = $award->where($where_per)->count();
                //分享奖励次数
                $where_fans['pid'] = $lottery['id'];
                $where_fans['openid'] = $openid;
                $where_fans['status'] = LotteryModel::FANS_ACTIVE;
                $share_play = M('redpacket_fans')->where($where_fans)->field('reserve')->find();
                $share_play = intval($share_play['reserve']);
                $share_play = ($share_play > 0) ? $share_play : 0;
                $game_chance2 = $share_play + $per_num - $per_num_record;
                if($game_chance2 < 0){
                    $game_chance2 = 0;
                }
            }
            if($number_limits == -1){
                if($per_num == -1){
                    $game_chance = -1;
                }else{
                    $game_chance = $game_chance2;
                }
            }else{
                if($game_chance1 == 0){
                    $game_chance = 0;
                }else{
                    if($per_num == -1){
                        $game_chance = -1;
                    }else{
                        $game_chance = $game_chance2;
                    }
                }
            }
            $this->ajaxReturn(array('code' => 0, 'errMsg' => 'ok', 'table_number' => 6, 'turntable' => $turntables,
                'title' => $lottery['title'], 'info' => $lottery['info'], 'force_follow' => $force_follow,
                'force_image' => $force_image, 'img_background' => $img_background, 'img_accept' => $img_accept,
                'img_again' => $img_again, 'img_share' => $img_share, 'img_custom' => $img_custom,
                'custom_choose' => $custom_choose, 'img_code' => $img_code, 'custom_link' => $custom_link,
                'follow_status' => $follow_status, 'game_chance' => $game_chance, 'share_able' => $lottery['share_able']));
        }else{
            $this->ajaxReturn(array('code' => 102, 'errMsg' => 'invalid id'));
        }
    }

    //大转盘盘面数据
    private function _turnTable($id)
    {
        $turntable = $table = array();
        $thanks = array('level' => 0, 'name' => '谢谢参与');
        //盘面，目前只有6面盘
        $where_item['redpacket_id'] = $id;
        $where_item['status'] = LotteryModel::ITEM_ACTIVE;
        $item = M('redpacket_item')->where($where_item)->order('id desc')->field('name,level')->limit(6)->select();
        $count = count($item);
        if(!empty($item)){
            $flag = array();
            $i = 1;
            foreach ($item as $value){
                $flag[] = $value['level'];
                $table[] = array(
                    'level' => $value['level'],
                    'name' => $value['name']
                );
            }
            array_multisort($flag, SORT_ASC, $table);
            if($count == 6){
                $turntable = $table;
            }elseif($count == 5){
                $turntable = $table;
                $turntable[5] = $thanks;
            }elseif($count == 4){
                $turntable[0] = $table[0];
                $turntable[1] = $table[1];
                $turntable[2] = $thanks;
                $turntable[3] = $table[2];
                $turntable[4] = $table[3];
                $turntable[5] = $thanks;
            }elseif($count == 3){
                $turntable[0] = $table[0];
                $turntable[1] = $table[1];
                $turntable[2] = $table[2];
                $turntable[3] = $table[1];
                $turntable[4] = $table[2];
                $turntable[5] = $thanks;
            }elseif($count == 2){
                $turntable[0] = $table[0];
                $turntable[1] = $table[1];
                $turntable[2] = $thanks;
                $turntable[3] = $table[0];
                $turntable[4] = $table[1];
                $turntable[5] = $thanks;
            }else{
                $turntable[0] = $table[0];
                $turntable[1] = $thanks;
                $turntable[2] = $table[0];
                $turntable[3] = $thanks;
                $turntable[4] = $table[0];
                $turntable[5] = $thanks;
            }
            foreach ($turntable as &$value_table){
                $value_table['order'] = $i;
                $i++;
            }
        }else{
            for($i=0;$i<6;$i++){
                $turntable[] = array(
                    'order' => $i+1,
                    'level' => 0,
                    'name' => '谢谢参与'
                );
            }
        }
        return $turntable;
    }

    //抽奖操作
    public function playLottery()
    {
        $id = I('get.id', -1);
        if($id == -1){
            $this->ajaxReturn(array('code' => 101, 'errMsg' => 'required parameter missing'));
        }
        $where['id'] = $id;
        $where['keyword'] = $this->_project;
        $where['status'] = LotteryModel::STATUS_ACTIVE;
        $lottery = M('redpacket')->where($where)->find();
        if(!empty($lottery)){
            //正常活动时间内
            $time = date('Y-m-d H:i:s');
            if($lottery['startdate'] > $time){
                $this->ajaxReturn(array('code' => 103, 'errMsg' => 'not start'));
            }
            if($time > $lottery['enddate']) {
                $this->ajaxReturn(array('code' => 104, 'errMsg' => 'already end'));
            }
            $this->_token = $lottery['token'];
            //剩余抽奖次数
            $game_chance = $this->_gameChance($lottery);
            if($game_chance == -1 || $game_chance > 0){
                //判断是否中奖
                $winLottery = $this->_winLottery($lottery['total_rate']);
                if($winLottery){
                    //中奖了
                    $this->_saveAwardWin($id);
                }else{
                    //未中奖
                    $this->_saveAwardEmpty($id);
                }
            }elseif($game_chance == -2){
                //未中奖
                $this->_saveAwardEmpty($id);
            }else{
                $this->ajaxReturn(array('code' => 105, 'errMsg' => 'no chance'));
            }
        }else{
            $this->ajaxReturn(array('code' => 102, 'errMsg' => 'invalid id'));
        }
    }

    //剩余抽奖次数，game_chance0没次数，-1无限制，-2直接去中空奖
    private function _gameChance($lottery)
    {
        $game_chance = -1;
        $day_start = date("Y-m-d") . " 00:00:00";
        $day_end = date("Y-m-d") . " 23:59:59";
        $award = M('redpacket_fansaward');
        //每日游戏次数上限
        $number_limits = intval($lottery['number_limits']);
        if($number_limits != -1){
            $where_limit['pid'] = $lottery['id'];
            $where_limit['status'] = array('neq', LotteryModel::AWARD_DELETE);
            $where_limit['createdate'] = array('between', array($day_start, $day_end));
            $number_limits_record = $award->where($where_limit)->count();
            if($number_limits > $number_limits_record){
                $game_chance = $number_limits - $number_limits_record;
            }else{
                $game_chance = 0;
                return $game_chance;
            }
        }
        //每日中奖次数上限（达到上限也要让别人玩下去，即空奖）
        $day_limit = intval($lottery['reserve']);
        if($day_limit != -1){
            $where_day['pid'] = $lottery['id'];
            $where_day['zhongjiang'] = LotteryModel::ZHONGJIANG_ACTIVE;
            $where_day['status'] = array('neq', LotteryModel::AWARD_DELETE);
            $where_day['createdate'] = array('between', array($day_start, $day_end));
            $day_limit_record = $award->where($where_day)->count();
            if($day_limit > $day_limit_record){
                $game_chance = $day_limit - $day_limit_record;
            }else{
                $game_chance = -2;
                return $game_chance;
            }
        }
        $openid = session('lottery_openid_'.$lottery['id']);
        if(!$openid){
            $this->ajaxReturn(array('code' => 108, 'errMsg' => 'openid missing'));
        }
        //每人每日游戏次数上限
        $per_num = intval($lottery['per_num']);
        if($per_num != -1){
            $where_per['pid'] = $lottery['id'];
            $where_per['openid'] = $openid;
            $where_per['status'] = array('neq', LotteryModel::AWARD_DELETE);
            $where_per['createdate'] = array('between', array($day_start, $day_end));
            $where_per['reserve'] = LotteryModel::LOTTERY_NORMAL;
            $per_num_record = $award->where($where_per)->count();
            //分享奖励次数
            $where_fans['pid'] = $lottery['id'];
            $where_fans['openid'] = $openid;
            $where_fans['status'] = LotteryModel::FANS_ACTIVE;
            $share_play = M('redpacket_fans')->where($where_fans)->field('reserve')->find();
            $share_play = intval($share_play['reserve']);
            if(($share_play + $per_num) > $per_num_record){
                $game_chance = $share_play + $per_num - $per_num_record;
                $game_chance = ($game_chance > 0) ? $game_chance : 0;
            }else{
                $game_chance = 0;
                return $game_chance;
            }
        }
        //每人中奖次数上限（达到上限也要让别人玩下去，即空奖）
        $per_num_sum = intval($lottery['per_num_sum']);
        if($per_num_sum != -1){
            $where_sum['pid'] = $lottery['id'];
            $where_sum['openid'] = $openid;
            $where_sum['zhongjiang'] = LotteryModel::ZHONGJIANG_ACTIVE;
            $where_sum['status'] = array('neq', LotteryModel::AWARD_DELETE);
            $per_num_sum_record = $award->where($where_sum)->count();
            if($per_num_sum > $per_num_sum_record){
                $game_chance = $per_num_sum - $per_num_sum_record;
            }else{
                $game_chance = -2;
                return $game_chance;
            }
        }
        return $game_chance;
    }

    //模拟判断是否中奖
    private function _winLottery($total_rate)
    {
        if($total_rate <= 0){
            return false;
        }
        $range = $total_rate * 100000;
        $random = rand(1, 10000000);
        if($random <= $range){
            return true;
        }
        return false;
    }

    //插入中奖信息
    private function _saveAwardWin($id)
    {
        //奖品是否还有剩余
        $stock = $this->_stock($id);
        if(!empty($stock)){
            //按照顺序队列产生奖品
            $award_id = $this->_logic($stock);
            //事务回滚，防止中奖个数超过奖品数
            $this->_checkAwardWin($id, $award_id);
        }else{
            $this->_saveAwardEmpty($id);
        }
    }

    //插入空奖信息
    private function _saveAwardEmpty($id)
    {
        $openid = session('lottery_openid_'.$id);
        if(!$openid){
            $this->ajaxReturn(array('code' => 108, 'errMsg' => 'openid missing'));
        }
        //分享奖励次数
        $where_fans['pid'] = $id;
        $where_fans['openid'] = $openid;
        $where_fans['status'] = LotteryModel::FANS_ACTIVE;
        $share_play = M('redpacket_fans')->where($where_fans)->field('reserve')->find();
        $share_play = intval($share_play['reserve']);
        $data = array(
            'token' => $this->_token,
            'pid' => $id,
            'openid' => $openid,
            'award_id' => 0,
            'zhongjiang' => LotteryModel::ZHONGJIANG_DELETE,
            'status' => LotteryModel::AWARD_ACTIVE,
            'reserve' => LotteryModel::LOTTERY_NORMAL
        );
        //剩余游戏次数
        $day_start = date("Y-m-d") . " 00:00:00";
        $day_end = date("Y-m-d") . " 23:59:59";
        $where['id'] = $id;
        $lottery = M('redpacket')->where($where)->field('per_num')->find();
        $per_num = intval($lottery['per_num']);
        if($per_num != -1){
            $where_per['pid'] = $id;
            $where_per['openid'] = $openid;
            $where_per['status'] = array('neq', LotteryModel::AWARD_DELETE);
            $where_per['createdate'] = array('between', array($day_start, $day_end));
            $where_per['reserve'] = LotteryModel::LOTTERY_NORMAL;
            $per_num_record = M('redpacket_fansaward')->where($where_per)->count();
            $game_chance = $per_num + $share_play - $per_num_record - 1;
            $game_chance = ($game_chance > 0) ? $game_chance : 0;
        }else{
            $game_chance = -1;
        }
        //大转盘移动位置
        $turntable = $this->_turnTable($id);
        $order = 0;
        foreach ($turntable as $value_table){
            if($value_table['level'] == 0){
                $order = $value_table['order'];
                break;
            }
        }
        //优先减去分享得到游戏机会
        if($share_play > 0){
            $data['reserve'] = LotteryModel::LOTTERY_SHARE;
            M('redpacket_fans')->where($where_fans)->setDec('reserve', 1);
        }
        $added = M('redpacket_fansaward')->add($data);
        if($added !== false){
            $this->ajaxReturn(array('code' => 0, 'errMsg' => 'thanks', 'win' => 0, 'order' => $order,
                'game_chance' => $game_chance));
        }else{
            $this->ajaxReturn(array('code' => 150, 'errMsg' => 'server error'));
        }
    }

    //剩余奖品数
    private function _stock($id)
    {
        //总库存
        $where['redpacket_id'] = $id;
        $where['number'] = array('gt', 0);
        $where['status'] = LotteryModel::ITEM_ACTIVE;
        $items = M('redpacket_item')->where($where)->field('id,number')->select();
        $awardItems = $awardIds = $usedItems = $stock = array();
        if(!empty($items)){
            foreach ($items as $value){
                $awardItems[$value['id']] = intval($value['number']);
                $awardIds[] = $value['id'];
            }
            //已消耗库存
            $where_used['pid'] = $id;
            $where_used['award_id'] = array('in', $awardIds);
            $where_used['zhongjiang'] = LotteryModel::ZHONGJIANG_ACTIVE;
            $where_used['status'] = array('neq', LotteryModel::AWARD_DELETE);
            $used = M('redpacket_fansaward')->where($where_used)->field('award_id')->select();
            if(!empty($used)){
                foreach ($used as $value_used){
                    $usedItems[$value_used['award_id']]++;
                }
                //剩余库存
                if(!empty($awardItems)){
                    foreach ($awardItems as $key => $value_item){
                        $difference = isset($usedItems[$key]) ? ($value_item - $usedItems[$key]) : $value_item;
                        if($difference > 0){
                            $stock[$key] = $difference;
                        }
                    }
                }
            }else{
                //剩余库存
                $stock = $awardItems;
            }
        }
        arsort($stock);
        return $stock;
    }

    //优化中奖时奖品的获得顺序
    private function _logic($stock)
    {
        $cycle = $award_id = 0;
        if(!empty($stock)){
            $stock_len = count($stock);
            while($cycle < $stock_len){
                $i = 1;
                $current_stock = $except_current_stock = $current_award_id = 0;
                foreach ($stock as $key => $value){
                    if($i == 1){
                        $current_stock = $value;
                        $current_award_id = $key;
                    }else{
                        $except_current_stock += $value;
                    }
                    $i++;
                }
                //中奖顺序 todo 10 2 1
                if(count($stock) == 1){
                    $award_id = $current_award_id;
                    break;
                }elseif($current_stock / $except_current_stock >= 2){
                    $award_id = $current_award_id;
                    break;
                }else{
                    //删除数组队列的第一个元素
                    unset($stock[$current_award_id]);
                    $cycle++;
                }
            }
        }
        return $award_id;
    }

    //事务回滚，防止中奖个数超过奖品数
    private function _checkAwardWin($id, $award_id)
    {
        $where['id'] = $id;
        $lottery = M('redpacket')->where($where)->find();
        $award = M("redpacket_fansaward");
        $openid = session('lottery_openid_'.$id);
        if(!$openid){
            $this->ajaxReturn(array('code' => 108, 'errMsg' => 'openid missing'));
        }
        //分享奖励次数
        $where_fans['pid'] = $id;
        $where_fans['openid'] = $openid;
        $where_fans['status'] = LotteryModel::FANS_ACTIVE;
        $share_play = M('redpacket_fans')->where($where_fans)->field('reserve')->find();
        $share_play = intval($share_play['reserve']);
        $data = array(
            'token' => $lottery['token'],
            'pid' => $id,
            'openid' => $openid,
            'award_id' => $award_id,
            'zhongjiang' => LotteryModel::ZHONGJIANG_ACTIVE,
            'status' => LotteryModel::AWARD_ACTIVE,
            'reserve' => LotteryModel::LOTTERY_NORMAL
        );
        $award->startTrans();
        //优先减去分享得到游戏机会
        if($share_play > 0){
            $data['reserve'] = LotteryModel::LOTTERY_SHARE;
            M('redpacket_fans')->where($where_fans)->setDec('reserve', 1);
        }
        $award->add($data);
        $day_start = date("Y-m-d") . " 00:00:00";
        $day_end = date("Y-m-d") . " 23:59:59";
        //每日游戏次数上限
        $number_limits = intval($lottery['number_limits']);
        if($number_limits != -1){
            $where_limit['pid'] = $lottery['id'];
            $where_limit['status'] = array('neq', LotteryModel::AWARD_DELETE);
            $where_limit['createdate'] = array('between', array($day_start, $day_end));
            if($_SERVER['HTTP_HOST'] == 'esm.zbxinmeiti.com'){
                $number_limits_record = M("redpacket_fansaward", 'esm_',
                    'mysql://yunwei_test:j9IrRtVtqcxEM@rm-bp145cj7u5r5k813u.mysql.rds.aliyuncs.com:3306/esm#utf8')
                    ->where($where_limit)->count();
            }else{
                $number_limits_record = $award->where($where_limit)->count();
            }
            if($number_limits_record > $number_limits){
                $award->rollback();
                $this->ajaxReturn(array('code' => 105, 'errMsg' => 'no chance'));
            }
        }
        //每日中奖次数上限（达到上限给别人中空奖）
        $day_limit = intval($lottery['reserve']);
        if($day_limit != -1){
            $where_day['pid'] = $lottery['id'];
            $where_day['zhongjiang'] = LotteryModel::ZHONGJIANG_ACTIVE;
            $where_day['status'] = array('neq', LotteryModel::AWARD_DELETE);
            $where_day['createdate'] = array('between', array($day_start, $day_end));
            if($_SERVER['HTTP_HOST'] == 'esm.zbxinmeiti.com'){
                $day_limit_record = M("redpacket_fansaward", 'esm_',
                    'mysql://yunwei_test:j9IrRtVtqcxEM@rm-bp145cj7u5r5k813u.mysql.rds.aliyuncs.com:3306/esm#utf8')
                    ->where($where_day)->count();
            }else{
                $day_limit_record = $award->where($where_day)->count();
            }
            if($day_limit_record > $day_limit){
                $award->rollback();
                $this->_saveAwardEmpty($lottery['id']);
            }
        }
        //每人每日游戏次数上限
        $per_num = intval($lottery['per_num']);
        if($per_num != -1){
            $where_per['pid'] = $lottery['id'];
            $where_per['openid'] = $openid;
            $where_per['status'] = array('neq', LotteryModel::AWARD_DELETE);
            $where_per['createdate'] = array('between', array($day_start, $day_end));
            $where_per['reserve'] = LotteryModel::LOTTERY_NORMAL;
            if($_SERVER['HTTP_HOST'] == 'esm.zbxinmeiti.com'){
                $per_num_record = M("redpacket_fansaward", 'esm_',
                    'mysql://yunwei_test:j9IrRtVtqcxEM@rm-bp145cj7u5r5k813u.mysql.rds.aliyuncs.com:3306/esm#utf8')
                    ->where($where_per)->count();
            }else{
                $per_num_record = $award->where($where_per)->count();
            }
            if($per_num_record > ($per_num + $share_play)){
                $award->rollback();
                $this->ajaxReturn(array('code' => 105, 'errMsg' => 'no chance'));
            }
            $game_chance = $per_num + $share_play - $per_num_record;
            $game_chance = ($game_chance > 0) ? $game_chance : 0;
        }else{
            $game_chance = -1;
        }
        //每人中奖次数（达到上限给别人中空奖）
        $per_num_sum = intval($lottery['per_num_sum']);
        if($per_num_sum != -1){
            $where_sum['pid'] = $lottery['id'];
            $where_sum['openid'] = $openid;
            $where_sum['zhongjiang'] = LotteryModel::ZHONGJIANG_ACTIVE;
            $where_sum['status'] = array('neq', LotteryModel::AWARD_DELETE);
            if($_SERVER['HTTP_HOST'] == 'esm.zbxinmeiti.com'){
                $per_num_sum_record = M("redpacket_fansaward", 'esm_',
                    'mysql://yunwei_test:j9IrRtVtqcxEM@rm-bp145cj7u5r5k813u.mysql.rds.aliyuncs.com:3306/esm#utf8')
                    ->where($where_sum)->count();
            }else{
                $per_num_sum_record = $award->where($where_sum)->count();
            }
            if($per_num_sum_record > $per_num_sum){
                $award->rollback();
                $this->_saveAwardEmpty($lottery['id']);
            }
        }
        //奖项库存数（达到上限给别人中空奖）
        $where_item['id'] = $award_id;
        $where_item['status'] = LotteryModel::ITEM_ACTIVE;
        $item = M('redpacket_item')->where($where_item)->field('number,name,level')->find();
        if(!empty($item)){
            //已消耗奖品
            $where_used['pid'] = $lottery['id'];
            $where_used['award_id'] = $award_id;
            $where_used['zhongjiang'] = LotteryModel::ZHONGJIANG_ACTIVE;
            $where_used['status'] = array('neq', LotteryModel::AWARD_DELETE);
            if($_SERVER['HTTP_HOST'] == 'esm.zbxinmeiti.com'){
                $used_count = M("redpacket_fansaward", 'esm_',
                    'mysql://yunwei_test:j9IrRtVtqcxEM@rm-bp145cj7u5r5k813u.mysql.rds.aliyuncs.com:3306/esm#utf8')
                    ->where($where_used)->count();
            }else{
                $used_count = $award->where($where_used)->count();
            }
            if($used_count > $item['number']){
                $award->rollback();
                $this->_saveAwardEmpty($lottery['id']);
            }else{
                $award->commit();
                //大转盘移动位置
                $turntable = $this->_turnTable($lottery['id']);
                $order = 0;
                foreach ($turntable as $value_table){
                    if($value_table['level'] == $item['level']){
                        $order = $value_table['order'];
                        break;
                    }
                }
                $this->ajaxReturn(array('code' => 0, 'errMsg' => 'congratulations', 'win' => 1,
                    'name' => $item['name'], 'order' => $order, 'game_chance' => $game_chance));
            }
        }else{
            $award->rollback();
            $this->_saveAwardEmpty($lottery['id']);
        }
    }

    //提交中奖信息
    public function saveUserInfo()
    {
        $id = I('post.id', -1);
        $name = I('post.name', '');
        $phone = I('post.phone', '');
        $address = I("post.address", '', '');
        if($id == -1){
            $this->ajaxReturn(array('code' => 101, 'errMsg' => 'required parameter missing'));
        }
        if($name == ''){
            $this->ajaxReturn(array('code' => 106, 'errMsg' => 'name missing'));
        }
        if($phone == ''){
            $this->ajaxReturn(array('code' => 107, 'errMsg' => 'phone missing'));
        }
        $openid = session('lottery_openid_'.$id);
        if(!$openid){
            $this->ajaxReturn(array('code' => 108, 'errMsg' => 'openid missing'));
        }
        $where['pid'] = $id;
        $where['openid'] = $openid;
        $where['status'] = LotteryModel::FANS_ACTIVE;
        $updated = M('redpacket_fans')->where($where)->save(array('name' => $name, 'phone' => $phone, 'address' => $address));
        if($updated !== false){
            $this->ajaxReturn(array('code' => 0, 'errMsg' => 'ok'));
        }else{
            $this->ajaxReturn(array('code' => 150, 'errMsg' => 'server error'));
        }
    }

    //微信分享成功增加抽奖次数
    public function shareLottery()
    {
        $id = I('get.id', -1);
        if($id == -1){
            $this->ajaxReturn(array('code' => 101, 'errMsg' => 'required parameter missing'));
        }
        $openid = session('lottery_openid_'.$id);
        if(!$openid){
            $this->ajaxReturn(array('code' => 108, 'errMsg' => 'openid missing'));
        }
        $where['id'] = $id;
        $where['keyword'] = $this->_project;
        $where['status'] = LotteryModel::STATUS_ACTIVE;
        $lottery = M('redpacket')->where($where)->field('token,share_play,per_num')->find();
        if(!empty($lottery)){
            $per_num = intval($lottery['per_num']);
            //剩余游戏次数
            $where_fans['pid'] = $id;
            $where_fans['openid'] = $openid;
            $where_fans['status'] = LotteryModel::FANS_ACTIVE;
            $fans_share = M('redpacket_fans')->where($where_fans)->field('reserve')->find();
            $fans_share = intval($fans_share['reserve']);
            $day_start = date("Y-m-d") . " 00:00:00";
            $day_end = date("Y-m-d") . " 23:59:59";
            if($per_num != -1){
                $where_per['pid'] = $id;
                $where_per['openid'] = $openid;
                $where_per['status'] = array('neq', LotteryModel::AWARD_DELETE);
                $where_per['createdate'] = array('between', array($day_start, $day_end));
                $where_per['reserve'] = LotteryModel::LOTTERY_NORMAL;
                $per_num_record = M('redpacket_fansaward')->where($where_per)->count();
                $game_chance = $per_num + $fans_share - $per_num_record;
                $game_chance = ($game_chance > 0) ? $game_chance : 0;
            }else{
                $game_chance = -1;
            }
            //是否已分享过
            $where_share['token'] = $lottery['token'];
            $where_share['openid'] = $openid;
            $where_share['url'] = C('SITE_URL').'/Wap/Lottery/index?id='.$id;
            $where_share['createdate'] = array('between', array($day_start, $day_end));
            $where_share['reserve'] = $this->_project;
            $record = M('wechat_share')->where($where_share)->find();
            if(!empty($record)){
                $this->ajaxReturn(array('code' => 0, 'errMsg' => 'ok', 'game_chance' => $game_chance));
            }else{
                //记录用户分享
                $data = array(
                    'token' => $lottery['token'],
                    'openid' => $openid,
                    'url' => C('SITE_URL').'/Wap/Lottery/index?id='.$id,
                    'reserve' => $this->_project
                );
                M('wechat_share')->add($data);
                $share_play = intval($lottery['share_play']);
                if($per_num != -1){
                    if($share_play > 0){
                        $game_chance = $game_chance + $share_play;
                    }
                    $game_chance = ($game_chance > 0) ? $game_chance : 0;
                }else{
                    $game_chance = -1;
                }
                if($share_play > 0){
                    $updated = M('redpacket_fans')->where($where_fans)->setInc('reserve', $share_play);
                    if($updated !== false){
                        $this->ajaxReturn(array('code' => 0, 'errMsg' => 'ok', 'game_chance' => $game_chance));
                    }else{
                        $this->ajaxReturn(array('code' => 150, 'errMsg' => 'server error'));
                    }
                }else{
                    $this->ajaxReturn(array('code' => 0, 'errMsg' => 'ok', 'game_chance' => $game_chance));
                }
            }
        }else{
            $this->ajaxReturn(array('code' => 102, 'errMsg' => 'invalid id'));
        }
    }

    //我的中奖信息
    public function getMyAward()
    {
        $id = I('get.id', -1);
        if($id == -1){
            $this->ajaxReturn(array('code' => 101, 'errMsg' => 'required parameter missing'));
        }
        $openid = session('lottery_openid_'.$id);
        if(!$openid){
            $this->ajaxReturn(array('code' => 108, 'errMsg' => 'openid missing'));
        }
        $where['award.pid'] = $id;
        $where['award.openid'] = $openid;
        $where['award.zhongjiang'] = LotteryModel::ZHONGJIANG_ACTIVE;
        $where['award.status'] = array('neq', LotteryModel::AWARD_DELETE);
        $where['item.status'] = LotteryModel::ITEM_ACTIVE;
        $award = M('redpacket_fansaward')->alias('award')
            ->join('LEFT JOIN esm_redpacket_item as item ON item.id = award.award_id')
            ->where($where)->order('award.id desc')->select();
        $awardList = array();
        $status = 0;
        if(!empty($award)){
            $status = 1;
            //是否填写信息
            $where_fans['pid'] = $id;
            $where_fans['openid'] = $openid;
            $where_fans['status'] = LotteryModel::FANS_ACTIVE;
            $fans = M('redpacket_fans')->where($where_fans)->field('name,phone')->find();
            if(!empty($fans['name']) && !empty($fans['phone'])){
                $status = 2;
            }
            foreach ($award as $value){
                $awardList[] = array(
                    'level' => LotteryModel::getLevel($value['level']),
                    'name' => $value['name']
                );
            }
        }
        $this->ajaxReturn(array('code' => 0, 'errMsg' => 'ok', 'list' => $awardList, 'status' => $status));
    }

    //关注微信公众号状态
    private function _followStatus($id)
    {
        $openid = session('lottery_openid_'.$id);
        if(empty($openid)){
            return false;
        }
        $token = $this->_getAccessToken();
        if(empty($token)){
            return false;
        }
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$token."&openid=".$openid."&lang=zh_CN";
        $res = $this->_curlGet($url);
        $res = json_decode($res, 1);
        if(isset($res['subscribe'])){
            if($res['subscribe'] == 1){
                return true;
            }else{
                return false;
            }
        }else{
            if(isset($res['errcode']) && $res['errcode'] == 40001){
                $url = "https://api.weixin.qq.com/cgi-bin/token?appid=" . $this->_wxuser['appid'] . "&secret=" .
                    $this->_wxuser['appsecret'] . "&grant_type=client_credential";
                $res = $this->_curlGet($url);
                $res = json_decode($res, 1);
                $token = isset($res['access_token']) ? $res['access_token'] : null;
                S( 'access_token_'.$this->_wxuser['token'], $token, 6300 );
                $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $token . "&openid=" . $openid .
                    "&lang=zh_CN";
                $res = $this->_curlGet($url);
                $res = json_decode($res, 1);
                if (isset($res['subscribe'])) {
                    if($res['subscribe'] == 1){
                        return true;
                    }else{
                        return false;
                    }
                } else {
                    return false;
                }
            }else if($res['errcode'] == 40003){
                $code = I("get.code", "", "");
                $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $this->_wxuser['appid'] .
                    "&secret=" . $this->_wxuser['appsecret'] . "&code=" . $code . "&grant_type=authorization_code";
                $exist = $this->_curlGet($url);
                $exist = json_decode($exist, 1);
                $exist = isset($exist['openid']) ? $exist : null;
                session('lottery_openid_'.$id, $exist);
                $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $token . "&openid=" . $exist .
                    "&lang=zh_CN";
                $res = $this->_curlGet($url);
                $res = json_decode($res, 1);
                if(isset($res['subscribe'])){
                    if($res['subscribe'] == 1){
                        return true;
                    }else{
                        return false;
                    }
                }else{
                    if (isset($res['errcode']) && $res['errcode'] == 40001) {
                        $url = "https://api.weixin.qq.com/cgi-bin/token?appid=" . $this->_wxuser['appid'] . "&secret=" .
                            $this->_wxuser['appsecret'] . "&grant_type=client_credential";
                        $res = $this->_curlGet($url);
                        $res = json_decode($res, 1);
                        $token = isset($res['access_token']) ? $res['access_token'] : null;
                        S( 'access_token_'.$this->_wxuser['token'], $token, 6300 );
                        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $token . "&openid=" .
                            $exist . "&lang=zh_CN";
                        $res = $this->_curlGet($url);
                        $res = json_decode($res, 1);
                        if (isset($res['subscribe'])) {
                            if($res['subscribe'] == 1){
                                return true;
                            }else{
                                return false;
                            }
                        } else {
                            return false;
                        }
                    }else{
                        return false;
                    }
                }
            }else{
                return false;
            }
        }
    }

    private function _getAccessToken()
    {
        $access_token = S( 'access_token_'.$this->_wxuser['token'] );
        if( !$access_token ){
            $url_get = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' .
                $this->_wxuser['appid'] . '&secret=' . $this->_wxuser['appsecret'];
            $json = json_decode($this->_curlGet($url_get));
            if (!$json -> errmsg){
                $access_token = $json -> access_token;
                S( 'access_token_'.$this->_wxuser['token'], $access_token, 6300 );
            }else{
                $this->error('获取access_token发生错误：错误代码'.$json->errcode.',微信返回错误信息：'.$json->errmsg);
            }
        }
        return $access_token;
    }

    private function _curlGet($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 500);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        $out = curl_exec($ch);
        curl_close($ch);
        return $out;
    }

    //手机设备型号
    private function _phoneType()
    {
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        if (stripos($user_agent, "iPhone") !== false) {
            $brand = 'iPhone';
        } else if (stripos($user_agent, "SAMSUNG") !== false || stripos($user_agent, "Galaxy") !== false
            || strpos($user_agent, "GT-") !== false || strpos($user_agent, "SCH-") !== false
            || strpos($user_agent, "SM-") !== false) {
            $brand = '三星';
        } else if (stripos($user_agent, "Huawei") !== false || stripos($user_agent, "Honor") !== false
            || stripos($user_agent, "H60-") !== false || stripos($user_agent, "H30-") !== false) {
            $brand = '华为';
        } else if (stripos($user_agent, "Lenovo") !== false) {
            $brand = '联想';
        } else if (strpos($user_agent, "MI-ONE") !== false || strpos($user_agent, "MI 1S") !== false
            || strpos($user_agent, "MI 2") !== false || strpos($user_agent, "MI 3") !== false
            || strpos($user_agent, "MI 4") !== false || strpos($user_agent, "MI-4") !== false) {
            $brand = '小米';
        } else if (strpos($user_agent, "HM NOTE") !== false || strpos($user_agent, "HM201") !== false) {
            $brand = '红米';
        } else if (stripos($user_agent, "Coolpad") !== false || strpos($user_agent, "8190Q") !== false
            || strpos($user_agent, "5910") !== false) {
            $brand = '酷派';
        } else if (stripos($user_agent, "ZTE") !== false || stripos($user_agent, "X9180") !== false
            || stripos($user_agent, "N9180") !== false || stripos($user_agent, "U9180") !== false) {
            $brand = '中兴';
        } else if (stripos($user_agent, "OPPO") !== false || strpos($user_agent, "X9007") !== false
            || strpos($user_agent, "X907") !== false || strpos($user_agent, "X909") !== false
            || strpos($user_agent, "R831S") !== false || strpos($user_agent, "R827T") !== false
            || strpos($user_agent, "R821T") !== false || strpos($user_agent, "R811") !== false
            || strpos($user_agent, "R2017") !== false) {
            $brand = 'OPPO';
        } else if (strpos($user_agent, "HTC") !== false || stripos($user_agent, "Desire") !== false) {
            $brand = 'HTC';
        } else if (stripos($user_agent, "vivo") !== false) {
            $brand = 'vivo';
        } else if (stripos($user_agent, "K-Touch") !== false) {
            $brand = '天语';
        } else if (stripos($user_agent, "Nubia") !== false || stripos($user_agent, "NX50") !== false
            || stripos($user_agent, "NX40") !== false) {
            $brand = '努比亚';
        } else if (strpos($user_agent, "M045") !== false || strpos($user_agent, "M032") !== false
            || strpos($user_agent, "M355") !== false) {
            $brand = '魅族';
        } else if (stripos($user_agent, "DOOV") !== false) {
            $brand = '朵唯';
        } else if (stripos($user_agent, "GFIVE") !== false) {
            $brand = '基伍';
        } else if (stripos($user_agent, "Gionee") !== false || strpos($user_agent, "GN") !== false) {
            $brand = '金立';
        } else if (stripos($user_agent, "HS-U") !== false || stripos($user_agent, "HS-E") !== false) {
            $brand = '海信';
        } else if (stripos($user_agent, "Nokia") !== false) {
            $brand = '诺基亚';
        } else {
            $brand = '未知';
        }
        return $brand;
    }

    //返回码
    public function getCode()
    {
        $code = array(
            101 => '参数缺少',
            102 => '活动不存在',
            103 => '活动未开始',
            104 => '活动已结束',
            105 => '没有抽奖次数了',
            106 => '请填写姓名',
            107 => '请填写联系方式',
            108 => 'OPENID丢失',
            150 => '系统异常，请重试',
        );
        $this->ajaxReturn(array('code' => $code));
    }
}